package com.taotao.rest.service.ipml;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.utils.JsonUtils;
import com.taotao.mapper.TbItemParamItemMapper;
import com.taotao.pojo.TbItemParamItem;
import com.taotao.pojo.TbItemParamItemExample;
import com.taotao.pojo.TbItemParamItemExample.Criteria;
import com.taotao.rest.dao.IJedisClient;
import com.taotao.rest.service.IItemParamItemService;

@Service
public class ItemParamItemServiceIpml implements IItemParamItemService {
	@Autowired
	private TbItemParamItemMapper itemParamItemMapper;

	@Autowired
	private IJedisClient jedisClient;

	@Value("${REDIS_ITEM_KEY}")
	private String REDIS_ITEM_KEY;

	@Value("${REDIS_ITEM_EXPIRE}")
	private Integer REDIS_ITEM_EXPIRE;

	@Override
	public TaotaoResult getItemParamById(Long itemId) {
		// 获取redis缓存中的内容
		try {
			String str = this.jedisClient.get(REDIS_ITEM_KEY + ":" + itemId
					+ ":param");
			if (StringUtils.isNotBlank(str)) {
				TbItemParamItem itemParamItem = JsonUtils.jsonToPojo(str,
						TbItemParamItem.class);
				return TaotaoResult.ok(itemParamItem);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		TbItemParamItemExample example = new TbItemParamItemExample();
		Criteria criteria = example.createCriteria();
		criteria.andItemIdEqualTo(itemId);
		// 通过商品id查询商品
		List<TbItemParamItem> itemParamItems = this.itemParamItemMapper
				.selectByExampleWithBLOBs(example);
		if (itemParamItems != null && !itemParamItems.isEmpty()) {
			TbItemParamItem itemParamItem = itemParamItems.get(0);
			// 向redis缓存中添加缓存
			try {
				String jsonStr = JsonUtils.objectToJson(itemParamItem);
				this.jedisClient.set(REDIS_ITEM_KEY + ":" + itemId + ":param",
						jsonStr);
				this.jedisClient.expire(REDIS_ITEM_KEY + ":" + itemId
						+ ":param", REDIS_ITEM_EXPIRE);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			return TaotaoResult.ok(itemParamItem);
		}
		return TaotaoResult.build(400, "商品描述信息不存在");
	}
}
